<template>
  <div class="user-info-container">
    <div class="profile-header">
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <img :src="userStore.loginUser?.avatar || '/src/assets/default_avatar.svg'" alt="用户头像" class="avatar-image" />
          <div class="avatar-overlay" @click="openUploadDialog" v-if="isEditing">
            <el-icon><Upload /></el-icon>
            <span>更换头像</span>
          </div>
        </div>
        <div class="user-info">
          <h2>{{ userStore.loginUser?.realname || '未设置姓名' }}</h2>
          <p>{{ userStore.loginUser?.username }}</p>
        </div>
      </div>
      <el-button type="primary" @click="handleEdit">编辑</el-button>
    </div>

    <div class="info-section">
      <div class="info-row">
        <div class="info-col">
          <div class="info-label">真实姓名</div>
          <div class="info-input">
            <el-input v-model="userInfo.realname" :disabled="!isEditing" placeholder="请输入真实姓名" />
          </div>
        </div>
        <div class="info-col">
          <div class="info-label">昵称</div>
          <div class="info-input">
            <el-input v-model="userInfo.username" :disabled="!isEditing" placeholder="请输入昵称" />
          </div>
        </div>
      </div>

      <div class="info-row">
        <div class="info-col">
          <div class="info-label">性别</div>
          <div class="info-input">
            <el-select v-model="userInfo.gender" :disabled="!isEditing" placeholder="请选择性别">
              <el-option :value="1" label="男" />
              <el-option :value="2" label="女" />
            </el-select>
          </div>
        </div>
        <div class="info-col">
          <div class="info-label">所在学校</div>
          <div class="info-input">
            <el-input v-model="userInfo.schoolName" disabled placeholder="所在学校" />
          </div>
        </div>
      </div>

      <div class="info-row">
        <div class="info-col">
          <div class="info-label">班级</div>
          <div class="info-input">
            <el-input v-model="classInfo" disabled placeholder="所在班级" />
          </div>
        </div>
        <div class="info-col">
          <div class="info-label">认证角色</div>
          <div class="info-input">
            <el-input v-model="roleText" disabled placeholder="认证角色" />
          </div>
        </div>
      </div>

      <div class="info-row">
        <div class="info-col">
          <div class="info-label">手机号码</div>
          <div class="info-input">
            <el-input v-model="userInfo.phoneNumber" :disabled="!isEditing" placeholder="请输入手机号码" />
          </div>
        </div>
        <div class="info-col">
          <div class="info-label">创建时间</div>
          <div class="info-input">
            <el-input v-model="userInfo.createdAt" disabled placeholder="创建时间" />
          </div>
        </div>
      </div>

      <div class="info-row" v-if="isEditing">
        <div class="actions">
          <el-button type="primary" @click="saveChanges">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="dialogVisible" title="上传头像" width="30%" center>
      <el-upload
        class="avatar-uploader"
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleAvatarChange">
        <img v-if="avatarUrl" :src="avatarUrl" class="preview-avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadAvatar" :loading="uploading">
            上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/userStore'
import { ElMessage } from 'element-plus'
import { updateUserInfoApi, uploadAvatarApi } from '../api/modules/user'
import { Upload, Plus } from '@element-plus/icons-vue'

// 获取用户存储
const userStore = useUserStore()

// 编辑状态
const isEditing = ref(false)

// 用户信息，从store中的loginUser复制
const userInfo = ref({})

// 头像上传相关状态
const dialogVisible = ref(false)
const avatarUrl = ref('')
const avatarFile = ref(null)
const uploading = ref(false)

// 计算班级信息展示
const classInfo = computed(() => {
  if (!userStore.loginUser?.grade && !userStore.loginUser?.classVal) return '未设置'
  return `${userStore.loginUser?.grade || ''}年级${userStore.loginUser?.classVal || ''}班`
})

// 计算用户角色文本
const roleText = computed(() => {
  const role = userStore.loginUser?.role
  if (role === 0) return '班主任'
  if (role === 1) return '校级管理员'
  if (role === 2) return '教育局管理员'
  return '未知角色'
})

// 初始化用户信息
onMounted(() => {
  initUserInfo()
})

// 初始化用户信息
const initUserInfo = () => {
  if (userStore.loginUser) {
    userInfo.value = { ...userStore.loginUser }
  }
}

// 处理编辑按钮点击
const handleEdit = () => {
  isEditing.value = true
}

// 保存更改
const saveChanges = async () => {
  try {
    // 调用API更新用户信息
    const result = await updateUserInfoApi(userInfo.value)
    
    // 检查API响应
    if (result.code === 1) {
      ElMessage.success('信息更新成功')
      
      // 更新本地存储的用户信息
      userStore.loginUser = { ...userInfo.value }
      localStorage.setItem('loginUser', JSON.stringify(userInfo.value))
      
      isEditing.value = false
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败，请稍后重试')
  }
}

// 取消编辑
const cancelEdit = () => {
  initUserInfo()
  isEditing.value = false
}

// 打开上传对话框
const openUploadDialog = () => {
  dialogVisible.value = true
  avatarUrl.value = ''
  avatarFile.value = null
}

// 处理头像选择变化
const handleAvatarChange = (file) => {
  avatarFile.value = file.raw
  avatarUrl.value = URL.createObjectURL(file.raw)
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) {
    ElMessage.warning('请先选择头像图片')
    return
  }

  uploading.value = true
  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('avatar', avatarFile.value)
    
    // 调用上传API
    const result = await uploadAvatarApi(formData)
    
    if (result.code === 1 && result.data) {
      // 更新用户头像
      userInfo.value.avatar = result.data.avatarUrl
      
      // 更新本地存储
      userStore.loginUser = { ...userInfo.value }
      localStorage.setItem('loginUser', JSON.stringify(userInfo.value))
      
      ElMessage.success('头像上传成功')
      dialogVisible.value = false
    } else {
      ElMessage.error(result.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请稍后重试')
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.user-info-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #e8f0fe 0%, #f8f9fa 100%);
  padding: 20px;
  border-radius: 8px 8px 0 0;
}

.avatar-section {
  display: flex;
  align-items: center;
}

.avatar-wrapper {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
  color: white;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay span {
  font-size: 12px;
  margin-top: 4px;
}

.user-info {
  margin-left: 20px;
}

.user-info h2 {
  font-size: 24px;
  margin: 0 0 5px 0;
  color: #333;
}

.user-info p {
  margin: 0;
  color: #666;
}

.info-section {
  padding: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 20px;
  gap: 20px;
}

.info-col {
  flex: 1;
}

.info-label {
  font-weight: 500;
  margin-bottom: 8px;
  color: #606266;
}

.info-input {
  width: 100%;
}

.actions {
  display: flex;
  justify-content: flex-start;
  margin-top: 20px;
  gap: 10px;
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.preview-avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}
</style> 